package com.reebake.ideal.org.util;

import cn.hutool.core.collection.CollUtil;
import com.reebake.ideal.model.TreeNode;
import com.reebake.ideal.org.entity.OrganizationDepartment;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class DepartmentUtil {

    public static List<TreeNode> toTree(List<OrganizationDepartment> departments) {
        List<TreeNode> nodes = new ArrayList<>();
        for(OrganizationDepartment department : departments) {
            if("0".equals(department.getParentId())) {
                TreeNode parent = toNode(department);
                parent.setIsLeaf(false);
                nodes.add(parent);
                findChildren(parent, departments);
            }
        }
        return nodes;
    }

    public static void findChildren(TreeNode node, List<OrganizationDepartment> departments) {
        for(OrganizationDepartment department : departments) {
            if(department.getParentId().equals(node.getValue())) {
                node.getChildren().add(toNode(department));
            }
        }
        List<TreeNode> children = node.getChildren();
        if(CollUtil.isEmpty(children)) {
            node.setIsLeaf(true);
            return;
        }else{
            node.setIsLeaf(false);
            for(TreeNode child : children) {
                findChildren(child, departments);
            }
        }
    }

    public static TreeNode toNode(OrganizationDepartment department) {
        TreeNode node = new TreeNode();
        node.setValue(department.getDepartmentId());
        node.setLabel(department.getDepartmentName());
        node.setParentId(department.getParentId());
        return node;
    }
}
